package com.zeta.plan.filter;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zeta.plan.model.JWTToken;
import com.zeta.plan.model.ResponseResult;
import com.zeta.plan.service.UserService;
import com.zeta.plan.utils.JWTUtil;
import com.zeta.plan.utils.SpringContextUtil;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName JWTFilter
 * @Description 自定义jwt过滤器
 * @Author zeta
 * @Date 2022/2/25 16:07
 * @Version 1.0
 **/
public class JWTFilter extends BasicHttpAuthenticationFilter {

    /**
     * 拦截器的前置方法，此处进行跨域处理
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));

        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
        }

        // 请求头中未携带token
        if (!isLoginAttempt(request, response)) {
            responseError(httpServletResponse, "no token");
            return false;
        }

        return super.preHandle(request, response);
    }

    /**
     * 是否进行登录请求
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String token = ((HttpServletRequest) request).getHeader("token");
        if (token != null) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否允许通过
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        try {
            return executeLogin(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            responseError(response, "shiro fail");
            return false;
        }
    }

    /**
     * 创建shiro token
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String token = ((HttpServletRequest) request).getHeader("token");
        if (token != null) {
            return new JWTToken(token);
        }
        return null;
    }


    /**
     * 成功拿到认证info后，执行该方法
     * 验证toke、刷新过期时间
     *
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        String jwtToken = (String) token.getPrincipal();
        String username = JWTUtil.getUsername(jwtToken);

        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        UserService userService = applicationContext.getBean(UserService.class);
        RedisTemplate<String, Object> redisTemplate = (RedisTemplate<String, Object>)applicationContext.getBean("redisTemplate");

        String secret = null;
        // 查询缓存
        Object secretValue = redisTemplate.opsForValue().get(username + ":secret");
        // 缓存未命中
        if (secretValue == null) {
            // 查询数据库
            secret = userService.findSecretByUsername(username);
            // 存入缓存
            redisTemplate.opsForValue().set(username + ":secret", secret, JWTUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS);
        } else { // 缓存命中
            secret = secretValue.toString();
        }
        if (jwtToken != null) {
            try {
                // 验证 jwtToken
                if (JWTUtil.verify(jwtToken, secret)) {
                    // 判断Redis中是否有 refreshToken
                    Object refreshTokenValue = redisTemplate.opsForValue().get(username + ":refreshToken");
                    if (refreshTokenValue == null) { // 用户已经登出
                        return false;
                    }
                    // 未登出
                    String refreshToken = refreshTokenValue.toString();
                    String createdTime = JWTUtil.getCreatedTime(jwtToken);
                    if (refreshToken.equals(createdTime)) {
                        return true;
                    }
                }
            } catch (TokenExpiredException e) { // token超时
                e.printStackTrace();
                // 刷新token
                return refreshToken(request, response, secret);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    /**
     * isAccessAllowed 返回 false时（验证失败），调用
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        this.sendChallenge(request, response);
        responseError(response, "token verify fail");
        return false;
    }


    private boolean refreshToken(ServletRequest request, ServletResponse response, String secret) {
        String token = ((HttpServletRequest) request).getHeader("token");
        String username = JWTUtil.getUsername(token);

        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);

        if (!redisTemplate.hasKey(username + ":refreshToken")) { // 不存在refreshToken（已登出）
            return false;
        }
        // 存在，刷新过期时间
        Long newCreatedTime = System.currentTimeMillis();
        HashMap<String, String> payload = new HashMap<>();
        payload.put("username", username);
        payload.put("createdTime",newCreatedTime.toString());
        String newToken = JWTUtil.createToken(newCreatedTime, payload, secret);
        // 刷新refreshToken
        redisTemplate.opsForValue().set(username + ":refreshToken", newCreatedTime);
        // 将新的token放入响应头中
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Authorization", token);
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "Authorization");
        return true;
    }

    private void responseError(ServletResponse response, String msg) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(401);
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json;charset=UTF-8");
        try {
            String om = new ObjectMapper().writeValueAsString(ResponseResult.unauthorized(msg));
            httpResponse.getWriter().append(om);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
